<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
    <div class="roles">
      <div id="aa"></div>
      <!--面包屑导航-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-divider></el-divider>

      <!--添加角色按钮-->
      <el-button @click="showaddDialog" type="success" plain>添加角色</el-button>
      <br><br>

      <!--表格-->
      <template>
        <el-table :data="rightList" border style="width: 100%">

          <el-table-column type="expand">
            <template v-slot:default="{ row }">
              <el-row class="l1" v-for="l1 in row.children" :key="l1.id">

                 <!-- 一级分类 -->
                <el-col :span="4">
                  <el-tag @close="delRight(row, l1.id)" closable>{{ l1.authName }}</el-tag>
                  <i class="el-icon-arrow-right"></i>
                </el-col>

                <el-col :span="20">
                  <el-row class="l2" v-for="l2 in l1.children" :key="l2.id">

                    <!-- 二级分类 -->
                    <el-col :span="4">
                      <el-tag @close="delRight(row, l2.id)" closable type="danger">{{ l2.authName }}</el-tag>
                      <i class="el-icon-arrow-right"></i>
                    </el-col>

                    <!-- 三级分类 -->
                    <el-col :span="20">
                        <el-tag @close="delRight(row, l3.id)" class="l3" closable type="success" v-for="l3 in l2.children" :key="l3.id">{{ l3.authName }}</el-tag>
                    </el-col>

                  </el-row>
                </el-col>

              </el-row>

            </template>
          </el-table-column>

          <el-table-column label="#" type="index"></el-table-column>

          <el-table-column prop="roleName" label="角色名称">
          </el-table-column>

          <el-table-column prop="roleDesc" label="描述">
          </el-table-column>

          <el-table-column label="操作">
            <!-- 使用插槽 -->
            <template v-slot:default="{ row }">
              <el-button @click="showEditDialog(row)" size="small" plain type="primary" icon="el-icon-edit"></el-button>
              <el-button @click="delUser(row.id, $event)" size="small" plain type="danger" icon="el-icon-delete"></el-button>
              <el-button @click="showAssignDialog(row)" size="small" plain type="success" icon="el-icon-check">分配角色</el-button>
            </template>
          </el-table-column>

        </el-table>
      </template>

      <!--添加角色-->
      <el-dialog
        @close="closeDialog"
        title="添加用户"
        :visible.sync="dialogVisible"
        width="30%"
        @keyup.enter.native="addUser"
        >

        <el-form :rules="rules" ref="form" :model="form" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>

          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="form.roleDesc" placeholder="请输入角色描述"></el-input>
          </el-form-item>
        </el-form>

        <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button @click="addUser" type="primary">确 定</el-button>
        </span>
        </template>

      </el-dialog>

      <!--编辑角色-->
      <el-dialog
        title="编辑角色"
        :visible.sync="editVisible"
        width="30%"
        @keyup.enter.native="editUser"
      >

        <el-form :rules="rules" ref="form" :model="form" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>

          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="form.roleDesc" placeholder="请输入角色描述"></el-input>
          </el-form-item>
        </el-form>

        <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button @click="editUser" type="primary">确 定</el-button>
        </span>
        </template>

      </el-dialog>

      <!--分配对话框-->
      <el-dialog
      title="分配权限"
      :visible.sync="assignVisible"
      width="35%">

        <el-tree
          ref="tree"
          node-key="id"
          show-checkbox
          default-expand-all
          :data="data"
          :props="defaultProps">
        </el-tree>

        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="assignVisible = false">取 消</el-button>
            <el-button @click="assignRights" type="primary">分 配</el-button>
          </span>
        </template>

      </el-dialog>

    </div>

</template>

<script>
export default {
  data () {
    return {
      // 表单数据
      rightList: [],
      // 添加角色框
      dialogVisible: false,
      // 添加角色值
      form: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 0, message: '不能为空', trigger: ['blur', 'change'] }],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'change' },
          { min: 0, message: '不能为空', trigger: ['blur', 'change'] }
        ]
      },
      // 编辑角色
      editVisible: false,
      // 显示隐藏分配对话框
      assignVisible: false,
      // 标记正在分配的角色id
      roleId: '',
      // 保存后台返回的数据
      data: [],
      // 树形结构展示的文字 配置
      defaultProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 封装渲染函数
    async getUserList () {
      const { meta, data } = await this.$axios.get(`roles`)
      if (meta.status === 200) {
        this.rightList = data
      } else {
        this.$message.error(meta.msg)
      }
    },

    // 添加角色显示
    showaddDialog () {
      this.dialogVisible = true
    },

    // 当关闭的时候进行清空输入框
    closeDialog () {
      this.$refs.form.resetFields()
    },

    // 添加角色
    async addUser () {
      try {
        // 表单校验
        await this.$refs.form.validate()
        const res = await this.$axios.post(`roles`, this.form)
        const { meta } = res
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          // 隐藏模态框
          this.dialogVisible = false
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 删除角色
    async delUser (id, e) {
      console.log(e.target)
      try {
        await this.$confirm('你确定要删除吗?', '温馨提醒', {
          type: '小个子'
        })
        const res = await this.$axios.delete(`roles/${id}`)
        const { meta } = res
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 编辑角色 =》 显示编辑框 回显数据
    showEditDialog (row) {
      // 显示编辑框
      this.editVisible = true
      // 回显数据
      this.form.id = row.id
      this.form.roleName = row.roleName
      this.form.roleDesc = row.roleDesc
    },

    // 编辑角色
    async editUser () {
      try {
        // 表单校验
        await this.$refs.form.validate()
        // 获取到发送ajax需要的值
        const { id, roleName, roleDesc } = this.form
        const { meta } = await this.$axios.put(`roles/${id}`, { roleName, roleDesc })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.editVisible = false
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 删除权限
    async delRight (row, rightId) {
      const res = await this.$axios.delete(`roles/${row.id}/rights/${rightId}`)
      const { meta, data } = res
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // 后台返回的数据是没有删除的数据 =》 所以说直接等于这个值即可
        row.children = data
      } else {
        this.$message.error(meta.msg)
      }
    },

    // 显示分配对话框
    async showAssignDialog (row) {
      // 保存roleId为了下面的修改发送ajax用
      this.roleId = row.id
      // 显示框
      this.assignVisible = true
      const res = await this.$axios.get(`rights/tree`)
      const { meta, data } = res
      if (meta.status === 200) {
        // 保存返回的数据
        this.data = data
        // 需要获取全部的三级权限的id, 用于设置
        const ids = []
        row.children.forEach(l1 => {
          row.children.forEach(l2 => {
            row.children.forEach(l3 => {
              ids.push(l3.id)
            })
          })
        })
        // 设置是否选中
        this.$refs.tree.setCheckedKeys(ids)
      } else {
        this.$message.error(meta.msg)
      }
    },

    // 分配进行修改发送ajax
    async assignRights () {
      // 获取全选的
      const ids = this.$refs.tree.getCheckedKeys()
      // 获取半选的
      const halfs = this.$refs.tree.getHalfCheckedKeys()
      // 结合
      const rids = [...ids, ...halfs].join(',')
      // 发送ajax进行修改
      const res = await this.$axios.post(`roles/${this.roleId}/rights`, { rids })
      const { meta } = res
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // 关闭对话框
        this.assignVisible = false
        // 重新渲染
        this.getUserList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style scoped lang="less">

  .l1 {
    margin-bottom: 10px;
    border-bottom: 1px dotted #ccc;
  }
  .l2 {
    margin-bottom: 10px;
  }
  .l3 {
    margin-right: 5px;
    margin-bottom: 5px;
  }

</style>
